package cn.comon.app.scan.service.analysis.impl;

import java.util.Properties;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.comon.app.scan.component.SysConfigBean;
import cn.comon.app.scan.entity.AsCheckresult;
import cn.comon.app.scan.entity.AsReportinfo;
import cn.comon.app.scan.service.AsCheckresultService;
import cn.comon.app.scan.service.AsReportinfoService;
import cn.comon.app.scan.service.analysis.IAnalysisResponse;
import cn.comon.app.scan.util.UtilTools;

/**
 * 网秦软件检测接口请求响应返回值处理
 * @author xujf
 *
 */
@Service("aqgjResponseImpl")
@Scope("prototype")
@Lazy(value=true)
@Transactional
public class AQGJAnalysisResponseImpl implements IAnalysisResponse {
    private static Logger logger = Logger.getLogger(AQGJAnalysisResponseImpl.class.getName());
    @Autowired
    private AsReportinfoService asReportinfoService;
    @Autowired
    private AsCheckresultService asCheckresultService;
    
	public void processResponse(Properties params, AsReportinfo asReportinfo, Object result) {
	    try {
	        logger.info("send result form AQGJ [Reportinfo ID:" + asReportinfo.getId() + "]:" + result.toString());
	        JSONObject jsonObj = JSONObject.fromObject(result);
	        //请求正确发送，检测结果正常的场合（无错误返回结果）
	        if (!jsonObj.containsKey("error_code")) {
	            AsCheckresult asCheckresultTMP = new AsCheckresult();
	            asCheckresultTMP.setRid(asReportinfo.getId());
	            asCheckresultTMP.setPackageUrlHash(asReportinfo.getPackageUrlHash());
	            asCheckresultTMP.setResultIndex(2);
                switch (jsonObj.getInt("level")) {
                case -1:
                    asCheckresultTMP.setSafeType(1);
                     break;
                case 0:
                    asCheckresultTMP.setSafeType(2);
                    break;
                case 1:
                    asCheckresultTMP.setSafeType(3);
                    break;
                case 2:
                    asCheckresultTMP.setSafeType(4);
                    break;
                case 3:
                    asCheckresultTMP.setSafeType(5);
                    break;
                case 4:
                    asCheckresultTMP.setSafeType(6);
                    break;
                }
                
	            asCheckresultTMP.setVirusName("");
	            asCheckresultTMP.setVirusDesc(jsonObj.getString("des"));
	            asCheckresultTMP.setResultDescr("");
	            
                if (jsonObj.containsKey("adplugin")) {
                    asCheckresultTMP.setAdinfo(jsonObj.getString("adplugin"));
                }
                if (jsonObj.containsKey("score")) {
                    asCheckresultTMP.setScore(jsonObj.getInt("score"));
                }
//	            asCheckresultTMP.setSize();
//	            asCheckresultTMP.setPlatform();
//                String official = "";
                if (jsonObj.containsKey("official")) {
                    asCheckresultTMP.setOfficial(jsonObj.getInt("official"));
                }
	            asCheckresultTMP.setCreateTime(UtilTools.getTimestamp(0));
	            asCheckresultTMP.setLastUpdateTime(UtilTools.getTimestamp(0));
	            //检索AsCheckresult表，确认该条记录是否曾经被同一家检测方检测过
	            //记录不存在，插入新记录
	            //记录存在，更新检测信息
	            AsCheckresult asCheckresult = asCheckresultService.findByID(asReportinfo.getId());
	            if (asCheckresult == null) {
	                asCheckresultService.addObj(asCheckresultTMP);
	            } else {
	                asCheckresultService.updateCheckresult(asCheckresultTMP);
	            }
	            
	            //AsReportinfo表更新（checkCount，expired，lastUpdateTime）
	            AsReportinfo asReportinfoTMP = new AsReportinfo();
	            asReportinfoTMP.setId(asReportinfo.getId());
	            //检测的结果(level)
	            //-1：安全性未知
	            //0：安全
	            //1：轻度风险
	            //2：中度风险
	            //3：重度风险
	            //4：谨慎使用
	            int expired = 0;
	            switch (jsonObj.getInt("level")) {
	                case -1:
	                     expired = Integer.parseInt(SysConfigBean.getProperty("result.safetype.unknown")); //推后5天再扫描
	                     break;
	                case 0:
                        //检测结果为安全
                        expired = Integer.parseInt(SysConfigBean.getProperty("result.safetype.safe")); //推后180天再扫描
	                    break;
	                default:
	                    expired = Integer.parseInt(SysConfigBean.getProperty("result.safetype.dangerous"));
	                    break;
	            }
	            //Expired过期时间，SQL语句更新
	            asReportinfoTMP.setExpired(expired);
	            asReportinfoTMP.setCheckTime(UtilTools.getTimestamp(0));
	            asReportinfoService.updateReportinfo(asReportinfoTMP);
	        }
	    } catch (Exception e) {
	        logger.error(e);
	        }
	    }
}